﻿using Microsoft.Phone.Controls;
using BismillahReader.Core;
using System.Windows.Controls;

namespace BismillahReader
{
    public partial class Main : PhoneApplicationPage
    {
        QuranTranslation _translation;
        public Main()
        {            
            InitializeComponent();
        }

        void _translation_OnLoadComplete(QuranTranslation translation)
        {
            this.DataContext = _translation;
            lstSurah.ItemsSource = translation.SurahTranslations.Values;
            this.PageTitle.Text = "In the name of Allah";
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (AppContext.Translation == null)
            {
                _translation = new QuranTranslation(AppContext.CurrentTranslation.Url);
                _translation.OnLoadComplete += new QuranTranslation.LoadComplete(_translation_OnLoadComplete);
                AppContext.Translation = _translation;
                _translation.Load();
            }
            else
            {
                _translation = AppContext.Translation;
                _translation_OnLoadComplete(_translation);
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            if (AppContext.Translation.IsLoaded)
            {
                lstSurah.ItemsSource = null;
            }
        }

        private void HyperlinkButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            HyperlinkButton btn = e.OriginalSource as HyperlinkButton;
            if (btn != null)
            {
                SurahTranslation translation = btn.DataContext as SurahTranslation;
                AppContext.Surah = translation;
                NavigationService.Navigate(new System.Uri(string.Format("/SurahView.xaml?no=", translation.No), System.UriKind.Relative));
            }
        }

    }
}